using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TuyennvLibrary.Reflection;
using TuyennvLibrary.SqlClient;
namespace TuyennvLibrary.ServerApi.Models
{
    public class Application
    {
        public string appid { get; set; }
        public string name { get; set; }
        public string api_key { get; set; }
        public string private_key { get; set; }
        public string config { get; set; }
        public string class_api { get; set; }
        public string sender_id { get; set; }
        public int type_app { get; set; }
        public int type_version { get; set; }
        public string description { get; set; }
        public string developer { get; set; }
        public int status { get; set; }
        public DateTime createddate { get; set; }
        public string file_dll { get; set; }
        public int status_advertise { get; set; }
        public int platform { get; set; }
        public string filep12 { get; set; }
        public string passp12 { get; set; }
        public int AdvId { get; set; }
        public int AdvPopupId { get; set; }

        public static string COLUMN_APPID = "appid";
        public static string COLUMN_NAME = "name";
        public static string COLUMN_API_KEY = "api_key";
        public static string COLUMN_PRIVATE_KEY = "private_key";
        public static string COLUMN_CONFIG = "config";
        public static string COLUMN_CLASS_API = "class_api";
        public static string COLUMN_SENDER_ID = "sender_id";
        public static string COLUMN_TYPE_APP = "type_app";
        public static string COLUMN_TYPE_VERSION = "type_version";
        public static string COLUMN_DESCRIPTION = "description";
        public static string COLUMN_DEVELOPER = "developer";
        public static string COLUMN_STATUS = "status";
        public static string COLUMN_CREATEDDATE = "createddate";
        public static string COLUMN_FILE_DLL = "file_dll";
        public static string COLUMN_STATUS_ADVERTISE = "status_advertise";
        public static string COLUMN_PLATFORM = "platform";
        public static string COLUMN_ADVID = "AdvId";
        public static string COLUMN_ADVPOPUPID = "AdvPopupId";
        public static string COLUMN_FILEP12 = "filep12";
        public static string COLUMN_PASSP12 = "passp12";
        public static string TableName = "application";
        public Application()
        {
            this.appid = string.Empty;
            this.name = string.Empty;
            this.api_key = string.Empty;
            this.private_key = string.Empty;
            this.config = JsonConvert.SerializeObject(new { version = "0"});
            this.class_api = string.Empty;
            this.sender_id = string.Empty;
            this.type_app = 0;
            this.type_version = 0;
            this.description = string.Empty;
            this.developer = string.Empty;
            this.status = 0;
            this.createddate = DateTime.Now;
            this.file_dll = string.Empty;
            this.platform = 1;
            this.status_advertise = 1;
            this.AdvId = 0;
            this.AdvPopupId = 0;
            this.filep12 = string.Empty;
            this.passp12 = string.Empty;
        }
        public List<DescriptionMethod> getDocumentApi(HttpServerUtility Server,string pagedevapi,HttpRequest Request)
        {
            string domain = Request.Url.ToString().Replace(Request.Url.AbsolutePath, "").Replace(Request.Url.Query,"");
            string pathDll = string.Empty;
            if (!string.IsNullOrEmpty(this.file_dll))
            {

                pathDll = Server.MapPath(TuyennvLibrary.ServerApi.Controllers.Config.DirFileDLL + this.file_dll);
            }
            return  TuyennvLibrary.ServerApi.Controllers.ApiController.getListDescriptionApi(pathDll, this.class_api, this.appid, domain+"/"+pagedevapi);
        }
        public object ToObject(Func<Application, object> predicate)
        {
            return predicate(this);
        }
        
    }
    public class ApplicationModel:BaseModel<Application>
    {
        public ApplicationModel()
        {
            table = Application.TableName;
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Insert(Application obj)
        {
            try
            {
                DB.Insert(table, new SqlParameter[] {
                    new SqlParameter("appid",obj.appid),
					new SqlParameter("name",obj.name),
					new SqlParameter("api_key",obj.api_key),
					new SqlParameter("private_key",obj.private_key),
					new SqlParameter("config",obj.config),
					new SqlParameter("class_api",obj.class_api),
					new SqlParameter("sender_id",obj.sender_id),
					new SqlParameter("type_app",obj.type_app),
					new SqlParameter("type_version",obj.type_version),
					new SqlParameter("description",obj.description),
					new SqlParameter("developer",obj.developer),
					new SqlParameter("status",obj.status),
					new SqlParameter("createddate",obj.createddate),
                    new SqlParameter("file_dll",obj.file_dll),
                    new SqlParameter("filep12",obj.filep12),
                    new SqlParameter("passp12",obj.passp12),
                    new SqlParameter("status_advertise",obj.status_advertise),
                    new SqlParameter("platform",obj.platform),
                    new SqlParameter("AdvId",obj.AdvId),
                    new SqlParameter("AdvPopupId",obj.AdvPopupId),
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Update(Application obj)
        {
            try
            {
                DB.Update(table, new SqlParameter[] {
					new SqlParameter("name",obj.name),
					new SqlParameter("api_key",obj.api_key),
					new SqlParameter("private_key",obj.private_key),
					new SqlParameter("config",obj.config),
					new SqlParameter("class_api",obj.class_api),
					new SqlParameter("sender_id",obj.sender_id),
					new SqlParameter("type_app",obj.type_app),
					new SqlParameter("type_version",obj.type_version),
					new SqlParameter("description",obj.description),
					new SqlParameter("developer",obj.developer),
					new SqlParameter("status",obj.status),
					new SqlParameter("createddate",obj.createddate),
                    new SqlParameter("file_dll",obj.file_dll),
                    new SqlParameter("filep12",obj.filep12),
                    new SqlParameter("passp12",obj.passp12),
                    new SqlParameter("status_advertise",obj.status_advertise),
                    new SqlParameter("platform",obj.platform),
                    new SqlParameter("AdvId",obj.AdvId),
                    new SqlParameter("AdvPopupId",obj.AdvPopupId),
                }, new SqlParameter[]{
					new SqlParameter("appid",obj.appid),
																																																												 
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool UpdateAvertise(string appid, string field, int advid)
        {
            try
            {
                DB.Update(table, new SqlParameter[] {
                    new SqlParameter(field,advid),
                }, new SqlParameter[]{
					new SqlParameter("appid",appid),
																																																												 
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool UpdateConfig(string appid, string config)
        {
            try
            {
                DB.Update(table, new SqlParameter[] {
					new SqlParameter("config",config),

                }, new SqlParameter[]{
					new SqlParameter("appid",appid),
																																																												 
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        public bool addConfig(string appid, string key, object value)
        {
            Application app = GetByID(appid);
            JObject config = JObject.FromObject(JsonConvert.DeserializeObject(app.config));
            config[key] = new JValue(value);
            return UpdateConfig(appid, config.ToString());
        }
        public bool addConfig(string appid, string key, JObject json)
        {
            Application app = GetByID(appid);
            JObject config = JObject.FromObject(JsonConvert.DeserializeObject(app.config));
            config[key] = json;
            return UpdateConfig(appid, config.ToString());
        }
        public JObject getConfig(string appid)
        {
            Application app = GetByID(appid);
            JObject config = JObject.FromObject(JsonConvert.DeserializeObject(app.config));
            return config;
        }
        public JObject getConfig(string appid, string key)
        {
            Application app = GetByID(appid);
            JObject config = JObject.FromObject(JsonConvert.DeserializeObject(app.config));
            return (JObject)config[key];
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Delete(string appid)
        {
            try
            {
                DB.Delete(table, new SqlParameter[] { 
					new SqlParameter("appid",appid),
																																																												 
                });
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public bool DeleteMulti(string ListID)
        {
            try
            {
                if (ListID != string.Empty)
                {
                    foreach (string ID in ListID.Split(','))
                    {
                        Delete(ID);
                    }
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public List<Application> GetByPage(int page, int pagesize, List<Application> source)
        {
            List<Application> list = new List<Application>();
            int index = (page - 1) * pagesize;
            int count = source.Count;
            if (pagesize > count)
                list = source;
            else if (pagesize > count - index)
                list = source.GetRange(index, count - index);
            else
                list = source.GetRange(index, pagesize);
            return list;
        }
        public List<Application> GetListBy(DataTable dt)
        {
            List<Application> list = new List<Application>();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Application obj = GetBy(dr);
                    list.Add(obj);
                }
            }
            return list;
        }
        public DataTable GetListAll()
        {
            try
            {
                DataTable dt = DB.SelectDataTable(table);
                return dt;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public DataTable Search(string appid, string name)
        {
            string query = "select * from " + table + " where 1=1";
            if (!string.IsNullOrEmpty(appid))
            {
                query += string.Format(" and appid like '{0}%'", appid);
            }
            if (!string.IsNullOrEmpty(name))
            {
                query += string.Format(" and name like N'%{0}%'", name);
            }
            query += " order by CAST(appid as int) desc";
            DataTable dt = DB.ExecuteDataTable(query, null);
            return dt;
        }
        public DataTable Search(string appid, string name,int platform,int type_app)
        {
            string query = "select a.*,b.name as type_app_name from " + table + " a, "+TypeApplication.TableName+" b where a.type_app=b.id";
            if (!string.IsNullOrEmpty(appid))
            {
                query += string.Format(" and a.appid like '{0}%'", appid);
            }
            if (!string.IsNullOrEmpty(name))
            {
                query += string.Format(" and a.name like N'%{0}%'", name);
            }
            if (platform!=0)
            {
                query += string.Format(" and a.platform ={0}", platform);
            }
            if (type_app!=0)
            {
                query += string.Format(" and a.type_app ={0}", type_app);
            }
            this.Count = GetCountBy(query);
            if (page > 0)
            {
                query = GetQueryPagging(query,false, "CAST(a.appid as int) desc", page, pagesize);
            }
            else
            {
                query += " order by CAST(a.appid as int) desc";
            }
            DataTable dt = DB.ExecuteDataTable(query, null);
            return dt;
        }
        public Application GetBy(DataRow dr)
        {
            try
            {
                Application obj = new Application();
                obj.appid = (dr["appid"] is DBNull) ? string.Empty : dr["appid"].ToString();
                obj.name = (dr["name"] is DBNull) ? string.Empty : dr["name"].ToString();
                obj.api_key = (dr["api_key"] is DBNull) ? string.Empty : dr["api_key"].ToString();
                obj.private_key = (dr["private_key"] is DBNull) ? string.Empty : dr["private_key"].ToString();
                obj.config = (dr["config"] is DBNull) ? string.Empty : dr["config"].ToString();
                obj.class_api = (dr["class_api"] is DBNull) ? string.Empty : dr["class_api"].ToString();
                obj.sender_id = (dr["sender_id"] is DBNull) ? string.Empty : dr["sender_id"].ToString();
                obj.type_app = (dr["type_app"] is DBNull) ? 0 : int.Parse(dr["type_app"].ToString());
                obj.type_version = (dr["type_version"] is DBNull) ? 0 : int.Parse(dr["type_version"].ToString());
                obj.description = (dr["description"] is DBNull) ? string.Empty : dr["description"].ToString();
                obj.developer = (dr["developer"] is DBNull) ? string.Empty : dr["developer"].ToString();
                obj.status = (dr["status"] is DBNull) ? 0 : int.Parse(dr["status"].ToString());
                obj.createddate = (dr["createddate"] is DBNull) ? DateTime.Now : DateTime.Parse(dr["createddate"].ToString());
                obj.file_dll = (dr["file_dll"] is DBNull) ? string.Empty : dr["file_dll"].ToString();
                obj.filep12 = (dr["filep12"] is DBNull) ? string.Empty : dr["filep12"].ToString();
                obj.passp12 = (dr["passp12"] is DBNull) ? string.Empty : dr["passp12"].ToString();
                obj.status_advertise = (dr["status_advertise"] is DBNull) ? 0 : int.Parse(dr["status_advertise"].ToString());
                obj.platform = (dr["platform"] is DBNull) ? 0 : int.Parse(dr["platform"].ToString());
                obj.AdvId = (dr["AdvId"] is DBNull) ? 0 : int.Parse(dr["AdvId"].ToString());
                obj.AdvPopupId = (dr["AdvPopupId"] is DBNull) ? 0 : int.Parse(dr["AdvPopupId"].ToString());
                return obj;
            }
            catch (Exception)
            {
            }
            return new Application();
        }
        public Application GetBy(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    return GetBy(dr);
                }
            }
            return new Application();
        }
        
        public Application GetByID(string appid)
        {
            try
            {
                DataTable dt = DB.SelectDataTable(null, table, new SqlParameter[] { 
					new SqlParameter("appid",appid),
																																																												
                }, null);
                return GetBy(dt);
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void UpdateIdAdv(string column, int old_value, int value)
        {
            string query = "Update " + table + " set " + column + "=" + value + " where " + column + "= " + old_value;
            DB.ExecuteQuery(query, null);
        }
    }
}
